package com.zr.beijian.redis;

import com.zr.beijian.JPARepository.BeiJianJapRepository;
import com.zr.beijian.bean.BeiJian;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisRepository {
    @Autowired
    private BeiJianJapRepository beiJianJapRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    public BeiJian findOne(int id) {
        String key="findOne"+id;
        BeiJian beiJian =(BeiJian)redisTemplate.opsForValue().get(key);
        if(beiJian==null){
            synchronized (this){
                beiJian =(BeiJian)redisTemplate.opsForValue().get(key);
                if(beiJian==null){
                    beiJian = beiJianJapRepository.findOne(id);
                    redisTemplate.opsForValue().set(key,beiJian,10000,TimeUnit.DAYS);
                }
            }
        }
        return beiJian;
    }

    public void save(BeiJian beiJian) {
        String key="findOne"+beiJian.getId();
        //更新数据库
        beiJianJapRepository.save(beiJian);
        //更新缓存
        redisTemplate.opsForValue().set(key,beiJian,1,TimeUnit.DAYS);
    }

    public void delete(int id) {
        String key="findOne"+id;
        beiJianJapRepository.delete(id);
        redisTemplate.delete(key);
    }
}
